import React, { useEffect, useRef } from 'react'
import localImg from '../img/xiaomi.png'

export default function CanvasFill({ img: imgUrl, color }) {
  const canvasRef = useRef(null)
  const changeColor = hexToRgba(color ?? '#000000');
  const maxRender = useRef(7000)
  const currentRender = useRef(0)

  // 点击处的 x,y 和 imgdata 的 index 的对应关系
  function point2Index(x, y) {
    return (x + y * canvasRef.current.width) * 4;
  }

  // 16->rgba
  function hexToRgba(hex, opacity = 255) {
    return [parseInt('0x' + hex.slice(1, 3)), parseInt('0x' + hex.slice(3, 5)), parseInt('0x' + hex.slice(5, 7)), opacity]
  }

  // 获取图片点击地方的rgba值
  function getRgba(x, y, imgData) {
    const index = point2Index(x, y);
    return {
      r: imgData.data[index],
      g: imgData.data[index + 1],
      b: imgData.data[index + 2],
      a: imgData.data[index + 3],
    };
  }

  // 判断两个rgba颜色是否相同
  function diffColor(rgba1, rgba2) {
    // 返回 > 0 表示不相同
    return (
      Math.abs(rgba1.r - rgba2.r) +
      Math.abs(rgba1.g - rgba2.g) +
      Math.abs(rgba1.b - rgba2.b) +
      Math.abs(rgba1.a - rgba2.a)
    );
  }


  const click = (e) => {
    const canvas = canvasRef.current;
    const x = e.clientX - canvas.getBoundingClientRect().left
    const y = e.clientY - canvas.getBoundingClientRect().top

    console.info(x,y)

    const ctx = canvas.getContext('2d');

    // 获取imgdata
    const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    // 获取图片点击地方的rgba值
    const clickColor = getRgba(x, y, imgData);


    // 递归
    function _changeColor(x, y) {
      const stack = [[x, y]]
      currentRender.current = 0
      while (stack.length > 0) {
        currentRender.current++
        const [x, y] = stack.pop()
        const i = point2Index(x, y)
        const color = getRgba(x, y, imgData);

        if (x < 0 || x >= canvas.width || y < 0 || y >= canvas.height) continue;
        // 如果旁边颜色已经是changeColor停止
        if (diffColor(color, changeColor) === 0) continue;
        // 如果旁边的颜色相差太大停止
        if (diffColor(color, clickColor) > 50) continue;

        // 是否设置最大单次修改范围
        // if (currentRender.current >= maxRender.current) return

        imgData.data.set(changeColor, i);

        stack.push([x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1])
      }
    }



    // // 辅助函数，改变点击位置的rgba值
    // function _changeColor(x, y) {
    //   // 超过边界停止
    //   if (x < 0 || x >= canvas.width || y < 0 || y >= canvas.height) return;
    //   // 如果旁边的颜色相差太大停止
    //   const color = getRgba(x, y, imgData);
    //   if (diffColor(color, clickColor) > 50) return;
    //   // 如果旁边颜色已经是changeColor停止
    //   if (diffColor(color, changeColor) === 0) return;
    //   const index = point2Index(x, y);
    //   // 简写：从index开始，替换四个值
    //   imgData.data.set(changeColor, index);
    //   // 改变周围颜色
    //   _changeColor(x - 1, y);
    //   _changeColor(x + 1, y);
    //   _changeColor(x, y - 1);
    //   _changeColor(x, y + 1);
    // }
    _changeColor(x, y);
    // 改变图片
    ctx.putImageData(imgData, 0, 0);
  }

  useEffect(
    () => {
      const canvas = canvasRef.current;
      const width = canvas.width
      const height = canvas.height
      const context = canvas.getContext('2d');

      // 创建一个图像对象  
      const img = new Image();
      img.setAttribute('crossOrigin', 'anonymous')
      img.src = imgUrl ?? 'https://ts1.cn.mm.bing.net/th/id/R-C.60ab7683045a6268b660b6a5a0a68665?rik=WZKpDNrJDhycWQ&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fb%2f2021%2f04-01%2f98823%2fbeijing_pic_98823_1200_600.jpg&ehk=LjgDX7earOYUE2FbY3rXutxlFXupvf16b%2fYYDI1dZow%3d&risl=&pid=ImgRaw&r=0';

      img.onload = () => {
        // 在图像加载完成后绘制到 Canvas  
        context.drawImage(img, 0, 0, width, height);
      };

      // 可选: 清理画布  
      return () => {
        context.clearRect(0, 0, canvas.width, canvas.height);
      };
    }, [imgUrl]
  )

  return (
    <div className='main_canvas_container'>
      <canvas onClick={click} ref={canvasRef} id='my_canvas' width={900} height={450}></canvas>
    </div>
  )
}
